<?php
class User extends CActiveRecord
{
    const STATUS_ADMIN = 9;
    const STATUS_INACTIVE = 0;
    const STATUS_MEMBER = 1;
    const STATUS_BANNED = -1;

    const VALIDATION_TYPE_ACTIVATE = 1;

    public $rePassword = '';
    public $AgreeTerms = '';
    public $AuthenticateStatus = null;
    
    public $YearOfBirth = '';
    public $Birthday = '';
    public $Gender = 'Male';
    public $Avatar = '';
    public $ReceiveNewsletter; // receive newsletter or not
    //public $verifyCode;
    public $dateCreated = array('from'=>'','to'=>'');
    
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }
    
    public function tableName()
    {
        return 'users';
    }

    /**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'Id' => 'Id',
			'Username' => 'Username',
			'Password' => 'Password',
            'Name' => 'Name',
			'Email' => 'Email',
			'CreatedDate' => 'Created date',
			'LastLogin' => 'Last login',
			'ValidationCode' => 'Validation code',
			'ValidationType' => 'Validation type',
			'ValidationExpired' => 'Validation expired',
			'Status' => 'Status',
		);
	}
    
    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
	    return array(
	        array('Username', 'required', 'on' => 'register, edit', 'message' => Yii::t('user/User','USERNAME_REQUIRED')),
            array('Username', 'on' => 'register, edit', 'usernameExists'),
            array('Name', 'required', 'on' => 'register, edit', 'message' => Yii::t('user/User','NAME_REQUIRED')),
            
            array('Email', 'required', 'on' => 'register, edit', 'message' => Yii::t('user/User','EMAIL_REQUIRED')),
            array('Email', 'email', 'on' => 'register, edit', 'message' => Yii::t('user/User','EMAIL_NOT_VALID')),
            array('Email', 'emailExists', 'on' => 'register, edit'), 
            
            array('Password', 'required', 'on' => 'register', 'message' => Yii::t('user/User','PASSWORD_REQUIRED')),            
            array('Password', 'length', 'on' => 'register, edit', 'min' => 5, 'max' => 32, 'message' => Yii::t('user/User','PASSWORD_LENGTH')),
            array('rePassword', 'compare', 'compareAttribute' => 'Password', 'on' => 'register, edit', 'message' => Yii::t('user/User', 'PASSWORD_NOT_MATCH')),
            
	        /*array('Username', 'required', 'on' => 'register, editProfile, editAccount'),
	        array('Username', 'usernameExists', 'on' => 'register, edit'),
	        
            array('Email', 'required', 'on' => 'register, editProfile, editAccount, login'),
	        array('Email', 'email'),
	        array('Email', 'emailExists', 'on' => 'register, edit'), 
	        
	        array('Password', 'required', 'on' => 'register, login'),			
	        array('Password', 'length', 'min' => 5, 'max' => 32, 'message' => 'Password must have at least 5 chars'),
			array('rePassword', 'compare', 'compareAttribute' => 'Password', 'on' => 'register, editAccount, update', 'message' => Yii::t('User', 'USER_PASSWORD_NOT_MATCH')),*/
	        
            //array('Avatar', 'file', 'types' => 'jpg, gif, png', 'maxSize'=>1024 * 1024 * 0.5 , 'tooLarge'=>'The file was larger than 500KB. Please upload a smaller file.', 'allowEmpty' => true, 'on' => 'register'),
            //array('YearOfBirth', 'numerical', 'integerOnly' => true, 'on' => 'register'),
            //array('YearOfBirth', 'required', 'on' => 'register'),
            //array('YearOfBirth', 'checkYearOfBirth', 'on' => 'register'),
            array('Name, Username, Email, Status, roles, dateCreated', 'safe', 'on' => 'search'),
        );
    }

    public function relations()
	{
		return array(
		    
		);
	}

    /**
     * @desc Check if username already exists
     */
    public function usernameExists($attribute, $params) {
        if (!$this->hasErrors($attribute))
		{
	        $user = User::model()->findByAttributes(array('Username' => $this->Username));
	        if (!is_null($user) && $user->Id != $this->Id)
	        {
	            $this->addError('Username', Yii::t('user/User', 'USERNAME_EXISTED'));
	            return false;
	    	}
        }
    }

    /**
     * @desc Check if email already exists
     */
    public function emailExists($attribute, $params) {
        if (!$this->hasErrors($attribute))
        {
            $user = User::model()->findByAttributes(array('Email' => $this->Email));
	        if (!is_null($user) && $user->Id != $this->Id){
	            $this->addError('Email', Yii::t('user/User', 'EMAIL_EXISTED'));
                return false;
            }
        }
    }

    public function checkYearOfBirth($attribute, $params)
    {
        if (!$this->hasErrors($attribute))
        {
            $curYear = date('Y');
            if (intval($curYear) - $this->YearOfBirth < 13)
            {
                $this->addError('YearOfBirth', Yii::t('User', 'USER_INVALID_YEAR_OF_BIRTH'));
                return false;
            }
        }
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('Username',$this->Username,true);
        $criteria->compare('Name',$this->Name,true);
        $criteria->compare('Email',$this->Email,true);
        $criteria->compare('Status',$this->Status);
        $criteria->compare('roles',$this->roles);
        
        // filter date_created - dateCreated
        if (is_array($this->dateCreated) && isset($this->dateCreated['from'], $this->dateCreated['to']) && (empty($this->dateCreated['from']) === false || empty($this->dateCreated['to']) === false)) {
            $from = $this->dateCreated['from'];
            $from = CDateTimeParser::parse($from, 'dd/MM/yyyy');
            if ($from === false) {
                $from = date('Y-m-d', strtotime('-1 years'));
            } else
                $from = date('Y-m-d', $from);
            $to = $this->dateCreated['to'];
            $to = CDateTimeParser::parse($to, 'dd/MM/yyyy');
            if ($to === false) {
                $to = date('Y-m-d', strtotime('+1 years'));
            } else
                $to = date('Y-m-d', $to);
            
            $criteria->addCondition("DATE(t.CreatedDate) BETWEEN DATE('".$from."') AND DATE('".$to."')");
        }
        
        return new CActiveDataProvider(get_class($this), array(
            'criteria'=>$criteria,
            'pagination'=>array(
                'pageSize'=>Settings::BO_PAGE_SIZE,
            ),
        ));
    }
    
    public function getRolesText() {
        if ($this->roles == ApplicationUser::ROLE_USERS)
            return "Thành viên bình thường";
        elseif ($this->roles == ApplicationUser::ROLE_ADMINISTRATORS)
            return "Quản trị website";
        else
            return '' ;
    }
    
    public function getStatusText()
    {
        if ($this->Status == 1)
            return "Hoạt động";
        elseif ($this->Status == 0)
            return "Bị khóa";
        else
            return '' ;
    }
    
    public function getRolesList()
    {
        return array(
            ApplicationUser::ROLE_USERS => 'Thành viên bình thường',
            ApplicationUser::ROLE_ADMINISTRATORS => 'Quản trị website (Administrator)',
        );
    }
    
    public function getDateWithFormat($field)
    {
        if ($this->$field == '0000-00-00' || $this->$field == '0000-00-00 00:00:00' || empty($this->$field))
            return '';
        return date('d/m/Y', strtotime($this->$field));
    }
    
    public function getActivateOrBannedIcon()
    {
        if ($this->Status == 1)
            return '<a title="Khóa tài khoản" class="lnk-activate-or-ban-user lnk-ban-user" id="action-user-'.$this->Id.'" href="#"><img width="16px" height="16px" src="'.Yii::app()->request->getBaseUrl(true).'/images/banned.png'.'" /></a>';
        elseif ($this->Status == 0)
            return '<a title="Kích hoạt tài khoản" class="lnk-activate-or-ban-user lnk-activate-user" id="action-user-'.$this->Id.'" href="#"><img width="16px" height="16px" src="'.Yii::app()->request->getBaseUrl(true).'/images/activate.png'.'" /></a>';
        else
            return '';
    }
}
?>
